﻿using Microsoft.Ajax.Utilities;
using PermissionBLL;
using PermissionCommon;
using PermissionEntity;
using PermissionWeb.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PermissionWeb.Controllers.SystemManager
{
    [JudgmentLogin]
    public class MenuController : Controller
    {
        // GET: Menu
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取所有的菜单栏信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllMenuInfo()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "Id" : Request["sort"];
            string order = Request["order"] == null ? "asc" : Request["order"];
            if (!string.IsNullOrEmpty(Request["MenuName"]) && !SqlInjection.GetString(Request["MenuName"]))
            {
                strWhere += " and Name like '%" + Request["MenuName"] + "%'";
            }
            // 获取前台传递过来的参数
            int pageIndex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);
            // 输出总数
            int totalCount = 0;
            // 输出结果
            string strJson = "";
            // 如果有逗号就是多列排序
            if (order.IndexOf(',') != -1)
            {
                // 拼接排序条件
                string sortMulti = "";
                string[] sortArray = sort.Split(',');
                string[] orderArray = order.Split(',');

                for (int i = 0; i < sortArray.Length; i++)
                {
                    sortMulti += sortArray[i] + " " + orderArray[i] + ",";
                }
                strJson = new MenuBLL().GetPager("tbMenu",
                    "Id,Name,ParentId,Code,LinkAddress,Icon,Sort,CreateTime,CreateBy,UpdateTime,UpdateBy",
                    sortMulti.Trim(','), pageSize, pageIndex, strWhere, out totalCount);
            }
            else
            {
                strJson = new MenuBLL().GetPager("tbMenu", "Id,Name,ParentId,Code,LinkAddress,Icon,Sort,CreateTime,CreateBy,UpdateTime,UpdateBy",
                    sort + " " + order, pageSize, pageIndex, strWhere, out totalCount);
            }
            var jsonResult = new { total = totalCount.ToString(), rows = strJson };
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuAdd()
        {
            return View();
        }

        /// <summary>
        /// 获取菜单树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllMenuTree()
        {
            string menuJson = new MenuBLL().GetAllMenu("");
            return Content(menuJson);
        }

        /// <summary>
        /// 新增菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddMenu()
        {
            try
            {
                UserEntity userModel = ViewData["Account"] as UserEntity;
                MenuEntity menuAddModel = new MenuEntity();
                menuAddModel.Name = Request["MenuName"];
                menuAddModel.Code = Request["MenuCode"];
                menuAddModel.Icon = Request["MenuIcon"];
                menuAddModel.LinkAddress = Request["MenuLinkAddress"];
                menuAddModel.Sort = Convert.ToInt32(Request["MenuSort"]);
                if (Request["MenuParentId"] != null && Request["MenuParentId"] != "")
                {
                    menuAddModel.ParentId = Convert.ToInt32(Request["MenuParentId"]);
                }
                else
                {
                    menuAddModel.ParentId = 0;
                }
                menuAddModel.CreateBy = menuAddModel.UpdateBy = userModel.AccountName;
                menuAddModel.CreateTime = menuAddModel.UpdateTime = DateTime.Now;
                int menuId = new MenuBLL().AddMenu(menuAddModel);
                if (menuId > 0)
                {
                    return Content("{\"msg\":\"添加成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"添加失败！\",\"success\":false}");
                }


            }
            catch (Exception ex)
            {

                return Content("{\"msg\":\"添加失败," + ex.Message + "\",\"success\":false}");
            }
        }

        /// <summary>
        /// 菜单编辑页面
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuEdit()
        {
            return View();
        }

        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult EditMenu()
        {
            try
            {
                UserEntity userModel = ViewData["Account"] as UserEntity;
                int id = Convert.ToInt32(Request["id"]);
                string originalName = Request["originalName"];
                MenuEntity menuEditModel = new MenuEntity();
                menuEditModel.Id = id;
                menuEditModel.Name = Request["MenuName"];
                menuEditModel.Code = Request["MenuCode"];
                menuEditModel.Icon = Request["MenuIcon"];
                menuEditModel.LinkAddress = Request["MenuLinkAddress"];
                menuEditModel.Sort = Convert.ToInt32(Request["MenuSort"]);
                if (Request["MenuParentId"] != null && Request["MenuParentId"] != "")
                {
                    menuEditModel.ParentId = Convert.ToInt32(Request["MenuParentId"]);
                }
                else
                {
                    menuEditModel.ParentId = 0;
                }
                menuEditModel.UpdateBy = userModel.AccountName;
                menuEditModel.UpdateTime = DateTime.Now;
                bool flag = new MenuBLL().EditMenu(menuEditModel, originalName);
                if (flag)
                {
                    return Content("{\"msg\":\"修改成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"修改失败！\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"修改失败," + ex.Message + "\",\"success\":false}");
            }
        }


        /// <summary>
        /// 删除菜单(根据Id)
        /// </summary>
        /// <returns></returns>
        public ActionResult DelMenuByIDs()
        {
            try
            {
                string Ids = Request["IDs"] == null ? "" : Request["IDs"];
                if (!string.IsNullOrEmpty(Ids))
                {
                    bool flag = new MenuBLL().DeleteMenu(Ids);
                    if (flag)
                    {
                        return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                    }
                    else
                    {
                        return Content("{\"msg\":\"删除失败！\",\"success\":false}");
                    }
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {

                return Content("{\"msg\":\"删除失败," + ex.Message + "\",\"success\":false}");
            }
        }

        /// <summary>
        /// 获取所有角色菜单树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllRoleMenuButtonTree()
        {
            int roleid = Convert.ToInt32(Request["roleid"]);
            string roleMenuJson = new MenuBLL().GetAllMenuButtonTree(roleid);
            return Content(roleMenuJson);
        }

        /// <summary>
        /// 分配按钮页面
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuButtonSet()
        {
            return View();
        }

        /// <summary>
        /// 分配按钮权限
        /// </summary>
        /// <returns></returns>
        public ActionResult SetMenuButton()
        {
            string menuid = Request["menuid"];
            string buttonids = Request["buttonids"];

            bool result = new MenuButtonBLL().SaveMenuButton(menuid, buttonids);
            if (result)
            {
                return Content("{\"msg\":\"分配按钮成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"分配按钮失败！\",\"success\":false}");
            }
        }

        public ActionResult MenuLinkAddressSelect()
        {
            return View();
        }

        public ActionResult GetLinkAddressFiles()
        {
            string path = Request["path"];
            string result = FilesHelper.GetFiles(path);
            return Content(result);
        }

        public ActionResult GetLinkAddressFileTitle()
        {
            string path = Request["path"];
            string result = FilesHelper.GetFileTitle(path);
            return Content(result);
        }

    }
}